package com.teen9g.infoplatformserver.service.impl;

import com.teen9g.dto.PostsAddDTO;
import com.teen9g.entity.Posts;
import com.teen9g.exception.PostContentNullException;
import com.teen9g.exception.PostNullException;
import com.teen9g.infoplatformserver.mapper.PostsMapper;
import com.teen9g.infoplatformserver.service.PostsService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class PostsServiceImpl implements PostsService {
    @Autowired
    private PostsMapper postsMapper;

    /**
     * 根据Id获取文章内容
     *
     * @param id
     * @return
     */
    @Override
    public String getPostsContentById(Integer id) {
        Posts contents = postsMapper.selectById(id);
        if (contents != null) {
            return contents.getPostContent();
        } else {
            throw new PostContentNullException("帖子内容不存在=_=");
        }
    }

    /**
     * 根据Id获取文章
     *
     * @param id
     * @return
     */
    @Override
    public Posts getPostsById(Integer id) {
        Posts posts = postsMapper.selectById(id);
        if (posts != null) {
            return posts;
        } else {
            throw new PostNullException("帖子不存在QAQ");
        }
    }

    /**
     * 添加帖子
     *
     * @param postsAddDTO
     */
    @Override
    public void addPosts(PostsAddDTO postsAddDTO) {
        Posts posts = new Posts();
        //复制属性
        BeanUtils.copyProperties(postsAddDTO, posts);
        posts.setPostDatetime(LocalDateTime.now());
        postsMapper.insert(posts);
    }

    /**
     * 获取所有帖子
     *
     * @return
     */
    @Override
    public List<Posts> getAllPosts() {
        return postsMapper.getAllPosts();
    }
}
